//
//  NSDictionaryCategory.m
//  ubixar-utils
//
//  Created by Demis Bellot on 17/04/2009.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "NSDictionaryCategory.h"

@implementation NSDictionary(NSDictionaryCategory)

-(NSDictionary *)dictionaryBySettingObject:(id)object forKey:(id<NSCopying>)key
{
    return [self dictionaryByAddingEntriesFromDictionary:[NSDictionary dictionaryWithObject:object forKey:key]];    
}

-(NSDictionary *)dictionaryBySettingObjects:(NSArray *)someObjects forKeys:(NSArray *)keys
{
    return [self dictionaryByAddingEntriesFromDictionary:[NSDictionary dictionaryWithObjects:someObjects forKeys:keys]];
}

-(NSDictionary *)dictionaryByAddingEntriesFromDictionary:(NSDictionary *)otherDictionary
{
    NSMutableDictionary * returnDictionary = [NSMutableDictionary dictionaryWithDictionary:self];
    [returnDictionary addEntriesFromDictionary:otherDictionary];
    return returnDictionary;
}

-(BOOL) boolForKey: (id) aKey
{
    BOOL result = NO; // lame default return value
    id <NSObject> obj = [self objectForKey:aKey];
    if (obj) {
        SEL bv = @selector(boolValue);
        if ([obj respondsToSelector:bv])
            result = ([obj performSelector:bv] ? YES : NO);
        else if ([obj isKindOfClass:[NSString class]]) {
            result = ([(NSString *)obj caseInsensitiveCompare: @"YES"] == NSOrderedSame);
            if (!result)
                result = ([(NSString *)obj caseInsensitiveCompare: @"TRUE"] == NSOrderedSame);
		}
	}
    return result;
}

-(int) intForKey: (id) aKey
{
    int result = 0; // lame default return value
    id <NSObject> obj = [self objectForKey:aKey];
    if (obj) {
        SEL iv = @selector(intValue);
        if ([obj respondsToSelector:iv])
            result = (int)[obj performSelector:iv];
	}
    return result;
}

-(BOOL) hasKey: (id) testKey
{
    return ([self objectForKey:testKey] != nil);
}

-(NSArray *)allObjectsSortedByKeySelector:(SEL)sortSelector
{
    NSArray *sortedKeys = [[self allKeys] sortedArrayUsingSelector:sortSelector];
    NSArray *resultArray = [self objectsForKeys:sortedKeys notFoundMarker:[NSNull null]];
    return resultArray;
}

- (NSDictionary *)resultsOfMakeObjectsPerformSelector:(SEL)selector
{
	NSArray *keys = [self allKeys];
	NSArray *values = [self objectsForKeys:keys notFoundMarker:nil];
	return [NSDictionary dictionaryWithObjects:[values resultsOfMakeObjectsPerformSelector:selector] forKeys:keys];
}

- (NSDictionary *)resultsOfMakeObjectsPerformSelector:(SEL)selector withObject:(id)object
{
	NSArray *keys = [self allKeys];
	NSArray *values = [self objectsForKeys:keys notFoundMarker:nil];
	return [NSDictionary dictionaryWithObjects:[values resultsOfMakeObjectsPerformSelector:selector withObject:object] forKeys:keys];
}

@end
